package com.xkh.common.config;

import com.xkh.common.common.constant.Result;
import org.springframework.validation.BindException;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.Objects;

/**
 * 全局异常处理类
 */
@RestControllerAdvice
public class GlobalExceptionHandler {

    @ResponseBody
    @ExceptionHandler(Exception.class)
    public Result<String> exceptionHandler(Exception e) {
        if (e instanceof BindException) {
            return Result.failure(Objects.requireNonNull(((BindException) e).getBindingResult().getFieldError()).getDefaultMessage());
        }
        e.printStackTrace();
        return Result.failure("您的服务器走神啦...");
    }
}
